package com.simpilemvc.web.servlet;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;

import com.simpilemvc.web.context.ActionModel;
import com.simpilemvc.web.context.HandlerMapping;
import com.simpilemvc.web.utils.ConfigParse;

/**
 * Servlet implementation class DispatcherServlet
 */
@WebServlet("/DispatcherServlet")
public class DispatcherServlet extends HttpServlet {
	
	private static final long serialVersionUID = -1710450720709050359L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = request.getRequestURI();
		ActionModel action = HandlerMapping.getMapping(path);
		if(action == null){
			throw new IllegalArgumentException("访问的路径不存在");
		}
		String result = doService(request,response,action);
		if(path.endsWith(".do")){
			String url = action.getResults().get(result);
			if(url == null || url == ""){
				toFail(request,response);
			} 
			request.getRequestDispatcher(url).forward(request, response);
		} else {
			response.getWriter().print(result);
		}
	}

	/**
	 * @author yangwenkui
	 * @throws IOException 
	 * @throws ServletException 
	 * @time 2016年10月28日 下午10:53:53
	 */
	private void toFail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/view/fail.jsp").forward(request, response);
	}

	/**
	 * @author yangwenkui
	 * @time 2016年10月28日 下午10:32:47
	 * @param request
	 * @param response
	 * @param action
	 * @return
	 */
	private String doService(HttpServletRequest request, HttpServletResponse response, ActionModel action) {
		try {
			Class<?> clazz = Class.forName(action.getType());
			Method method = clazz.getMethod(action.getMethod(),HttpServletRequest.class,HttpServletResponse.class);
			Object controller = clazz.newInstance();
			Object result = method.invoke(controller, request,response);
			return String.valueOf(result);
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalArgumentException(String.format("doService action=[%s] due to error",action.toString()));
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	private static final String defaultConfigFile = "/WEB-INF/simple-mvc-config.xml";
	
	@Override
	public void init() throws ServletException {
		ServletContext context = getServletContext();
		String xmlFile = context.getInitParameter("simpleMvcConfig");
		if(xmlFile == null || xmlFile.equals("")){
			xmlFile = defaultConfigFile;
		}
		String realPath = context.getRealPath("/");
		File file = new File(realPath + xmlFile);
		try {
			ConfigParse.parse(file);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}
